console.log('[urlSearch] 加载插件')

// tab id
var tabID = null
// 域名
var hosts = []

// popup 点击开始下载
function startWork() {
    console.log('[urlSearch] 发送startWork指令')
    sendMessageToContentScript({
        cmd: 'startWork'
    }, function (res) {
        if (res && res.type == 'startWork_callback') {
            localStorage['domain'] = res.data
        }
    })
}

function sendMessageToContentScript(message, callback) {
    // 下载文件时会弹出多个新Tab，原先页面可能不会被激活，需要使用旧的tabID进行通信
    if (tabID == null) {
        chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
            tabID = tabs.length ? tabs[0].id : null
            chrome.tabs.sendMessage(tabID, message, function (response) {
                if (callback) callback(response);
            });
        });
    } else {
        chrome.tabs.sendMessage(tabID, message, function (response) {
            if (callback) callback(response);
        });
    }
}

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    switch (request.cmd) {
        case 'saveLink':
            // localStorage[request.key] = request.data
            break
    }
});